﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace Models
{
  public static class MyHttpContext
  {
    public static IServiceCollection serviceCollection;
    public static void Init(IServiceCollection services)
    {
      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
        {
          options.TokenValidationParameters = new TokenValidationParameters()
          {
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero,
            ValidateIssuer = true,
            ValidIssuer = "Security:Tokens:Issuer",
            ValidateAudience = true,
            ValidAudience = "Security:Tokens:Audience",
            ValidateIssuerSigningKey = true,
            //AudienceValidator = (m, n, z) =>
            //{
            //  return true;
            //},
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Security:Tokens:Key"))
          };

          options.Events = new JwtBearerEvents
          {
            //JWT验证失败返回自定义
            OnChallenge = content =>
            {
              var code = "401";
              var msg = "请求未携带token，或携带的token无效！";
              if (content.ErrorDescription!=null && content.ErrorDescription.StartsWith("The token expired"))
              {
                code = "402";
                msg = "token已过期！";
              }
              content.HandleResponse();
              var payload = JsonConvert.SerializeObject(new { code, Message = msg });
              content.Response.ContentType = "application/json";
              content.Response.StatusCode = StatusCodes.Status200OK;
              content.Response.WriteAsync(payload);
              return Task.FromResult(0);
            },
            OnForbidden = content =>
            {
              var payload = JsonConvert.SerializeObject(new { code = "403", Message = "当前用户没有权限访问该接口！" });
              content.Response.ContentType = "application/json";
              content.Response.StatusCode = StatusCodes.Status200OK;
              content.Response.WriteAsync(payload);
              return Task.CompletedTask;
            }
          };
        });
    }

    public static HttpContext Current
    {
      get
      {
        object factory = serviceCollection.BuildServiceProvider().GetService(typeof(IHttpContextAccessor));
        Microsoft.AspNetCore.Http.HttpContext context = ((HttpContextAccessor)factory).HttpContext;
        return context;
      }
    }

  }
}
